package com.bmslz.monitor.base.config.grpc;

import io.grpc.netty.shaded.io.grpc.netty.GrpcSslContexts;
import io.grpc.netty.shaded.io.grpc.netty.NettyServerBuilder;
import io.grpc.netty.shaded.io.netty.handler.ssl.SslContextBuilder;
import net.devh.boot.grpc.server.serverfactory.GrpcServerConfigurer;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;

import javax.net.ssl.SSLException;
import java.io.File;

@Component
public class ServerConfig {

    @Value("${grpc.tls.enable}")
    private boolean tlsEnable;//是否开启tls传输
    @Value("${grpc.tls.ca}")
    private String ca;//证书
    @Value("${grpc.tls.key}")
    private String key;//证书私钥

    @Bean
    public GrpcServerConfigurer grpcServerConfigurer() {
        return serverBuilder -> {
            if (serverBuilder instanceof NettyServerBuilder) {
                try {
                    if (tlsEnable) {
                        ((NettyServerBuilder) serverBuilder).sslContext(getSslContextBuilder().build());
                    }
                } catch (SSLException e) {
                    throw new RuntimeException("Failed to create SSL context for gRPC server", e);
                }
            }
        };
    }

    private SslContextBuilder getSslContextBuilder() throws SSLException {
        File certChain = new File(ca);
        File privateKey = new File(key);

        return GrpcSslContexts.configure(
                SslContextBuilder.forServer(
                        certChain,
                        privateKey
                ));
    }
}
